package com.icesoft.core.common.util;

import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.KeyPair;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class PemFileUtils {
    private static final BouncyCastleProvider PROVIDER = new BouncyCastleProvider();

    public static KeyPair readKeyPair(String keyFilePath) throws IOException {
        PEMKeyPair pemKeyPair = readPemKeyPair(keyFilePath);
        return KeyPairUtils.convert(pemKeyPair);
    }

    public static X509Certificate readCertificate(String certificateFile) throws IOException, CertificateException {
        X509CertificateHolder x509CertificateHolder = readPemX509CertificateHolder(certificateFile);
        return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(x509CertificateHolder);
    }

    public static PEMKeyPair readPemKeyPair(String keyFilePath) throws IOException {
        return (PEMKeyPair) readPemFile(keyFilePath);
    }

    public static X509CertificateHolder readPemX509CertificateHolder(String certificateFile) throws IOException {
        return (X509CertificateHolder) readPemFile(certificateFile);
    }

    public static void writeCertificateToFile(String pemFilePath, X509Certificate certificate) throws IOException {
        writeToFile(pemFilePath, certificate);
    }

    public static void writeKeyPairToFile(String pemFilePath, KeyPair keyPair) throws IOException {
        writeToFile(pemFilePath, keyPair);
    }

    public static Object readPemFile(String pemFile) throws IOException {
        PEMParser pemParser = new PEMParser(new FileReader(pemFile));
        Object parsedObj = pemParser.readObject();
        pemParser.close();
        return parsedObj;
    }

    public static void writeToFile(String pemFilePath, Object object) throws IOException {
        File f = new File(pemFilePath);
        if (!f.getParentFile().isDirectory() && !f.getParentFile().mkdir()) {
            throw new IOException(
                    "couldn't create directory " + f.getParentFile().getAbsolutePath() + " for storing the SSL keystore");
        }
        JcaPEMWriter pem = new JcaPEMWriter(new FileWriter(f));
        pem.writeObject(object);
        pem.close();
    }
}
